﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinosLibrary;
using System.Windows.Markup;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Controls;
namespace BattleShip {
    [MessageProcess(MPType.PropClient, appName = "BattleShip")]
    public class PCShell : ModelLogic {
        [AutoWire]
        public DataClassesDataContext database;
        public IQueryable<int> ShellView {
            get {
                return database.Shells.Select(shell => shell.id);
            }
        }
        public PCShell() {
            DataTable dt = new DataTable("Shell");
            dt.Columns.Add(new DataColumn("name"));
            dt.Columns.Add(new DataColumn("value"));
            Property = dt;
        }
        public string ShellSource { get; set; }
        public string ShellType { get; set; }
        public int? CenterPoint { get; set; }
        public DataTable Property { get; set; }
        private int _Selection;
        public int Selection {
            get { return _Selection; }
            set {
                _Selection = value;
                Shell shell = database.Shells.Skip(value).First();
                ShellSource = shell.data;
                ShellType = shell.type;
                CenterPoint = shell.centerPoint;
                this.NotifyPropertyChanged(x => x.ShellSource);
                this.NotifyPropertyChanged(x => x.CenterPoint);
                this.NotifyPropertyChanged(x => x.ShellType);
                Property.Clear();
                using (MemoryStream ms = new MemoryStream(shell.property.ToArray())) {
                    Property.ReadXml(ms);
                }
                this.NotifyPropertyChanged(x => x.Property);
            }
        }
        public void AddNew() {
            database.Shells.InsertOnSubmit(fillShell(new Shell()));
            database.SubmitChanges();
            this.NotifyPropertyChanged(x => x.ShellView);
        }
        public void Update() {
            fillShell(database.Shells.Skip(_Selection).First());
            database.SubmitChanges();
        }
        private Shell fillShell(Shell shell) {
            using (MemoryStream ms = new MemoryStream()) {
                Property.WriteXml(ms);
                shell.centerPoint = CenterPoint;
                shell.property = ms.GetBuffer();
                shell.type = ShellType;
                shell.data = ShellSource;
            }
            return shell;
        }
    }
}
